//
//  YHNoticeVC.m
//  YiKaTongAPP
//  消息公告
//  Created by dev on 15/7/20.
//  Copyright (c) 2015年 YLZ-MAC. All rights reserved.
//

#import "YHNoticeVC.h"
#import "YHWebVC.h"
#import "MJRefresh.h"
#import "YHRequest.h"
#import "DataManager.h"

@interface YHNoticeVC ()<UITableViewDataSource,UITableViewDelegate>
{
    int pages;
    NSMutableString * ids;//用于更新已读消息
    
    UITableView * noticeTable;
    NSMutableArray * isReadArray;
    NSMutableArray * noticeArray;
}
@end

@implementation YHNoticeVC

@synthesize noticeArray;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"消息公告";
    
    self.automaticallyAdjustsScrollViewInsets =NO;
    
    noticeTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 66 , VERTICAL_SCREEN_WIDTH, VERTICAL_SCREEN_HEIGHT-64.0) style:UITableViewStyleGrouped];
    noticeTable.dataSource = self;
    noticeTable.delegate = self;
    noticeTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    noticeTable.backgroundColor= [UIColor whiteColor];
    [self.view addSubview:noticeTable];
    
    __unsafe_unretained __typeof(self) weakSelf = self;
    noticeTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        pages = 0;
        [weakSelf loadRequest];
    }];
    noticeTable.mj_footer = [MJRefreshAutoImageFooter footerWithRefreshingBlock:^{
        pages = pages+1;
        [weakSelf loadRequest];
    }];
    
    
    if (!noticeArray || noticeArray.count==0) {
        noticeArray = [NSMutableArray array];
        [noticeTable.mj_header beginRefreshing];
    }
    isReadArray = [DataManager readMutableArrarAtPathString:IS_READ_NOTICE];
    if (!isReadArray) {
        isReadArray = [NSMutableArray array];
    }
    ids = [NSMutableString string];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [DataManager writeNSMutableArrayToFile:isReadArray atPathName:IS_READ_NOTICE];
}

#pragma mark -


-(void)loadRequest
{
    int pageSize = noticeTable.frame.size.height / 30 +1;
    //获取列表
    //参数：pages、pageSize、noticeMold（全部0 公告1 消息2 消息未读0 消息已读1）0";
    
    NSString * url = [NSString stringWithFormat:@"%@?pages=%d&rows=%d",kNoticeUrl,pages,pageSize];
    NSData * data = nil;
    YHRequest * request = [[YHRequest alloc] init];
    
    [request postRequestWithUrl:url withData:data withSuccessed:^(id obj) {
        
        [self endRefreshing];
        if (obj && [obj isKindOfClass:[NSArray class]]) {
            NSArray * entity= (NSArray *)obj;
            if (entity.count==0) {
                [noticeTable.mj_footer endRefreshingWithNoMoreData];
            }else{
                [noticeTable.mj_footer resetNoMoreData];
            }
            if (pages > 0) {
                [noticeArray addObjectsFromArray:entity];
            }else{
                noticeArray= [[NSMutableArray alloc] initWithArray:entity copyItems:YES];
            }
            if(noticeArray.count==0){
                [self addErrorViewWithMsg:@"暂无通知"];
            }else{
                [self removeErrorView];
                [isReadArray addObjectsFromArray:noticeArray];
            }
            [noticeTable reloadData];
        }
        
    } withFailed:^(NSError *error) {
        
        [self endRefreshing];
        NSLog(@"请求失败：%@",error);
    }];

    
}


-(void)reloadActionWhenError
{
    [self removeErrorView];
    [noticeTable.mj_header beginRefreshing];
}

-(void)endRefreshing
{
    [noticeTable.mj_header endRefreshing];
    [noticeTable.mj_footer endRefreshing];
}

#pragma mark - tableView


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return noticeArray.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"announcementCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
    }
    NSDictionary * dic = [noticeArray objectAtIndex:indexPath.row];

    NSString * nid = [dic objectForKey:@"id"];
    
    cell.textLabel.text = [dic objectForKey:@"title"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@   %@",[dic objectForKey:@"createrName"],[dic objectForKey:@"createtime"]];
    
    [ids appendString:[NSString stringWithFormat:@"%@;",nid]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = [noticeArray objectAtIndex:indexPath.row];
    NSString * nid = [dic objectForKey:@"id"];
   
    BOOL isE = false;
    for (NSDictionary * temOld in isReadArray) {
        if ([temOld objectForKey:@"id"] == nid) {
            isE = true;
            break;
        }
    }
    if (!isE) {
        [isReadArray addObject:dic];
    }
    HYNoticeModel * model = [[HYNoticeModel alloc] init];
    model.title = [dic objectForKey:@"title"];
    model.creater = [dic objectForKey:@"createrName"];
    model.createtime = [dic objectForKey:@"createtime"];
    model.content = [dic objectForKey:@"content"];
    
    YHWebVC * vc = [[YHWebVC alloc] initWithNotice:model];
    [self.navigationController pushViewController:vc animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
